package com.hg.concurent.demo1;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: skh
 * @Date: 2019/10/17 16:23
 * @Description: 生产者-消费者模型
 */
public class MyContainer {

    private ReentrantLock lock = new ReentrantLock();
    private Condition producer = lock.newCondition();
    private Condition consumer = lock.newCondition();

    List<Integer> list = new LinkedList<>();

    private int count = 0;

    private int maxNum = 10;

    public void put(int i) {
        try {
            lock.lock();
            while (list.size() == maxNum) {
                //生产者满了
                try {
                    System.out.println("数据满了");
                    producer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            list.add(i);
            System.out.println("生产者"+Thread.currentThread().getName()+"生产数据:"+i);
            count++;
            consumer.signalAll();
        } finally {
            lock.unlock();
        }
    }

    public Integer get() {
        Integer result = null;
        try {
            lock.lock();
            while (list.size() == 0) {
                try {
                    System.out.println("数据为空");
                    consumer.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            result = list.remove(0);
            count--;
            producer.signalAll();
        } finally {
            lock.unlock();
        }
        return result;
    }

    public static void main(String[] args) {
        MyContainer myContainer = new MyContainer();
        Random random = new Random();


        //5个生产者 2个消费者
        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                while (true) {
                    Integer result = myContainer.get();
                    System.out.println("消费者"+Thread.currentThread().getName()+"获取数据:" + result);
                }
            }, "消费者" + i).start();
        }

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                while (true) {
                    myContainer.put(random.nextInt(20));
                }
            }, "生产者" + i).start();
        }


    }
}
